<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>AI聊天助手</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.7.2/css/all.min.css" rel="stylesheet">
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#333',     // 深灰（主色）
                        secondary: '#666',    // 中灰（辅助色）
                        neutral: '#f0f0f0',  // 浅灰（背景/输入框）
                        dark: '#1a1a1a',     // 深黑（文本色）
                        light: '#ffffff',     // 纯白
                    },
                    fontFamily: {
                        inter: ['Inter', 'sans-serif'],
                    },
                }
            }
        }
    </script>
    <style type="text/tailwindcss">
        @layer utilities {
            .scrollbar-hide::-webkit-scrollbar { display: none; }
            .message-appear { animation: messageAppear 0.3s ease forwards; }
            @keyframes messageAppear { from { opacity: 0; transform: translateY(10px); } to { opacity: 1; transform: translateY(0); } }
            .typing-indicator span { animation: typing-bounce 1.4s infinite ease-in-out both; }
            @keyframes typing-bounce { 0%, 80%, 100% { transform: scale(0); } 40% { transform: scale(1); } }
        }
    </style>
</head>
<body class="font-inter bg-gray-50 min-h-screen flex flex-col">
<!-- 聊天头部 -->
<header class="bg-primary text-white shadow-md z-10 relative p-4">
    <div class="flex items-center justify-between">
        <div class="flex items-center space-x-3">
            <div class="flex items-center">
                <img src="https://picsum.photos/200/200" alt="AI头像" class="w-10 h-10 rounded-full">
                <div class="ml-3">
                    <h1 class="text-lg font-semibold">AI助手</h1>
                    <p class="text-xs opacity-80">在线</p>
                </div>
            </div>
        </div>
        <div class="flex space-x-2">
            <button class="p-2 rounded-full hover:bg-primary/80">
                <i class="fa-solid fa-phone"></i>
            </button>
            <button class="p-2 rounded-full hover:bg-primary/80">
                <i class="fa-solid fa-ellipsis-v"></i>
            </button>
        </div>
    </div>
</header>

<!-- 聊天内容区域 -->
<main id="chat-container" class="flex-1 overflow-y-auto p-4 scrollbar-hide bg-light">
    <div class="flex items-start mb-4 message-appear">
        <img src="https://picsum.photos/200/200" alt="AI头像" class="w-8 h-8 rounded-full mr-2">
        <div class="max-w-[80%] bg-neutral p-3 rounded-lg rounded-tl-none shadow-sm">
            <p class="text-dark">你好！我是你的AI助手，有什么可以帮助你的吗？</p>
        </div>
    </div>
</main>

<!-- 输入区域 -->
<footer class="bg-white border-t border-gray-200 p-3 fixed bottom-0 left-0 right-0">
    <div class="flex items-center space-x-2">
        <button class="p-2 text-gray-500 hover:bg-gray-100 rounded-full">
            <i class="fa-solid fa-plus"></i>
        </button>
        <div class="flex-1 relative">
            <input id="message-input" type="text" placeholder="输入消息..."
                   class="w-full px-4 py-2 rounded-full bg-neutral border-0 focus:ring-2 focus:ring-primary/50">
            <button id="voice-btn" class="absolute right-2 top-1/2 transform -translate-y-1/2 p-1 text-gray-500 hover:text-primary">
                <i class="fa-solid fa-microphone"></i>
            </button>
        </div>
        <!-- 修复：将 text-black 改为 text-white，确保按钮文本可见 -->
        <button id="send-btn" class="bg-primary text-white p-2 rounded-full hover:bg-primary/90 z-10">
            <i class="fa-solid fa-paper-plane"></i>
        </button>
    </div>
</footer>

<script>
    document.addEventListener('DOMContentLoaded', () => {
        // 修复：添加对 chatContainer 的引用
        const chatContainer = document.getElementById('chat-container');
        const sendBtn = document.getElementById('send-btn');
        const messageInput = document.getElementById('message-input');

        sendBtn.addEventListener('click', () => {
            console.log('发送按钮被点击');
            sendMessage();
        });

        messageInput.addEventListener('keypress', (e) => {
            if (e.key === 'Enter' && !e.shiftKey) {
                e.preventDefault();
                console.log('按下回车键');
                sendMessage();
            }
        });
    });

    const sendMessage = async () => {
        // 修复：添加对 chatContainer 的引用
        const chatContainer = document.getElementById('chat-container');
        const message = document.getElementById('message-input').value.trim();
        if (!message) return;

        // 显示用户消息
        appendMessage('user', message);
        document.getElementById('message-input').value = '';
        scrollToBottom();

        // 显示输入中指示器
        const typingDiv = appendTypingIndicator();

        try {
            // 调用 Android 原生接口
            const aiResponse = await window.webobj.callAI(message);
            appendMessage('ai', aiResponse);
        } catch (error) {
            console.error('Error sending message:', error);

        } finally {
            if (typingDiv.parentNode) typingDiv.parentNode.removeChild(typingDiv);
        }
    };

    const appendMessage = (sender, message) => {
        // 修复：添加对 chatContainer 的引用
        const chatContainer = document.getElementById('chat-container');
        const div = document.createElement('div');
        div.className = `flex items-start mb-4 message-appear ${sender === 'user' ? 'justify-end' : ''}`;
        div.innerHTML = sender === 'ai' ?
            `<img src="https://picsum.photos/200/200" class="w-8 h-8 rounded-full mr-2">
             <div class="max-w-[80%] bg-neutral p-3 rounded-lg rounded-tl-none shadow-sm">
                 <p class="text-dark">${escapeHTML(message)}</p>
             </div>` :
            `<div class="max-w-[80%] bg-primary text-white p-3 rounded-lg rounded-tr-none shadow-sm">
                 <p>${escapeHTML(message)}</p>
             </div>
             <img src="https://picsum.photos/200/200?random=1" class="w-8 h-8 rounded-full ml-2">`;

        chatContainer.appendChild(div);
        return div;
    };

    const appendTypingIndicator = () => {
        // 修复：添加对 chatContainer 的引用
        const chatContainer = document.getElementById('chat-container');
        const div = document.createElement('div');
        div.className = 'flex items-start mb-4 message-appear';
        div.innerHTML = `
            <img src="https://picsum.photos/200/200" class="w-8 h-8 rounded-full mr-2">
            <div class="max-w-[80%] bg-neutral p-3 rounded-lg rounded-tl-none shadow-sm">
                <div class="typing-indicator">
                    <span></span><span></span><span></span>
                </div>
            </div>`;
        chatContainer.appendChild(div);
        return div;
    };

    const scrollToBottom = () => {
        // 修复：添加对 chatContainer 的引用
        const chatContainer = document.getElementById('chat-container');
        chatContainer.scrollTop = chatContainer.scrollHeight;
    };

    const escapeHTML = (str) => {
        return str.replace(/[&<"'>]/g, tag => ({
            '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#039;'
        }[tag]));
    };

    // 接收 Android 回调的 AI 回复
    window.receiveAIResponse = (result) => {
        // 修复：添加对 chatContainer 的引用
        const chatContainer = document.getElementById('chat-container');
        appendMessage('ai', result);
        scrollToBottom();
    };
</script>
</body>
</html>